import { createLibrary, updateLibrary } from "@/api/service/library/library";
import { ossUpload, uploadToServer } from "@/api/service/utils";
import { userStore } from "@/store/modules/user/user";
import { base64toFile } from "@/utils/file";
import { FileItem, Message } from "@arco-design/web-vue";
import { libraryForm } from "../data/form";
import { librarySizeData } from "../data/table";

const VIDEO_LIMIT = 5 * 1024 * 1024 * 1024 * 2024;
const t = translate("公共模块");
const getResolution = () => {
  return librarySizeData.value.find((e) => {
    if (e.sizeId === libraryForm.value.sizeId) {
      return e;
    }
    return null;
  });
};
/* 检测资源的大小 */
export const checkResource = (file: File) => {
  const sizeInfo = getResolution()!;
  return new Promise((res) => {
    if (libraryForm.value.type === "0") {
      const image = new Image();
      image.src = URL.createObjectURL(file);

      image.onload = () => {
        if (image.width === sizeInfo.width && image.height === sizeInfo.height) {
          res(true);
        }
        res(false);
      };
    } else if (libraryForm.value.type === "1") {
      if (file.size > VIDEO_LIMIT) {
        Message.warning(t.value?.["请选择小于5M的视频"]);
        res(false);
        return;
      }
      const video = document.createElement("video");
      video.src = URL.createObjectURL(file);
      video.hidden = true;
      video.muted = true;
      video.autoplay = true;
      const canvas = document.getElementById("canvas") as HTMLCanvasElement;
      const context = canvas.getContext("2d")!;

      video.addEventListener("loadeddata", async () => {
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        const base64 = canvas.toDataURL("image/webp").replace(`data:image/webp;base64,`, "");

        const cover = base64toFile(base64, `${nanoid()}.png`);
        const limitWidth = Math.abs(video.videoWidth - sizeInfo.width) < 5;
        const limitHeight = Math.abs(video.videoHeight - sizeInfo.height) < 5;
        if (limitWidth && limitHeight) {
          const coverData = await uploadMediaFile({
            uid: nanoid(),
            file: cover
          });
          const videoData = await uploadMediaFile({
            uid: nanoid(),
            file
          });
          if (coverData) {
            libraryForm.value.cover = coverData;
          }
          if (videoData) {
            libraryForm.value.uri = videoData;
          }
        }
      });
      video.onloadedmetadata = () => {
        const limitWidth = Math.abs(video.videoWidth - sizeInfo.width) < 5;
        const limitHeight = Math.abs(video.videoHeight - sizeInfo.height) < 5;
        if (limitWidth && limitHeight) {
          res(true);
          return;
        }
        res(false);
      };
    }
  });
};
const uploadMediaFile = async (file: FileItem): Promise<string | undefined> => {
  const store = userStore();
  if (!file.file) return;
  let href = "";

  if (store.$state.oss) {
    const { url } = await ossUpload({
      file: file.file,
      randomName: true,
      type: libraryForm.value.type
    });

    libraryForm.value.uri = url;

    libraryForm.value.bytes = file.file?.size || 0;
    href = url;
  } else {
    /* 上传到本地 */
    const { type } = libraryForm.value;
    const url = store.$state.paths[type];

    const { data } = await uploadToServer(`${url}`, file.file);

    if (data.code === 500) {
      Message.warning(data.msg);
    } else {
      Message.success(data.msg);
      href = data.data;
    }
  }
  return href;
};

const updateLibraryInfo = async () => {
  await updateLibrary(libraryForm.value);
};
const createMediaForm = async (file: FileItem) => {
  try {
    libraryForm.value.name = `${libraryForm.value.name}` || "Untitled";

    if (!file.file) return;
    libraryForm.value.uri = "";
    const url = await uploadMediaFile(file);
    if (url) {
      libraryForm.value.uri = url;
      let arr = url?.split(".");

      let format = arr[arr.length - 1];
      if (format) {
        libraryForm.value.format = format.toUpperCase();
      }
    }

    await createLibrary(libraryForm.value);
  } catch (error) {
    // console.log(error);
  }
};
export { createMediaForm, updateLibraryInfo, uploadMediaFile };
